package com.example.zsydb.service;


import com.example.zsydb.model.CalculationResult;
import com.example.zsydb.repository.PumpRepository;
import com.example.zsydb.repository.ResultRepository;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;

@Service
public class ScheduledTaskService {
    private static final Logger logger = LoggerFactory.getLogger(ScheduledTaskService.class);

    private final PumpRepository pRepository;
    private final PythonService pythonService;
    private final ResultRepository resultRepository;
    private final ObjectMapper objectMapper;

    @Autowired
    public ScheduledTaskService(PumpRepository pRepository,
                                PythonService pythonService,
                                ResultRepository resultRepository,
                                ObjectMapper objectMapper) {
        this.pRepository = pRepository;
        this.pythonService = pythonService;
        this.resultRepository = resultRepository;
        this.objectMapper = objectMapper;
    }


    public void fetchAndProcessData() {
        try {
            logger.info("🟢 开始自动执行..." + LocalDateTime.now());
            int page = 1;
            int size = 9999;
            String JH = "";
            logger.info("🟢 开始查询数据..."+ LocalDateTime.now());
            List<Map<String, Object>> data = pRepository.findAll(page, size,
                    JH);
//            System.out.println("data"+data);
            logger.info("🟢 进入python计算..."+ LocalDateTime.now());
            String pythonResult = pythonService.executePythonScript(data);
//            System.out.println("pythonResult"+pythonResult);
            JsonNode rootNode = objectMapper.readTree(pythonResult);
            JsonNode dataNode = rootNode.get("data");
            logger.info("🟢 开始存储数据..." + LocalDateTime.now());
            if (dataNode != null && dataNode.isArray()) {
                saveResultsInBatch(dataNode);
            }
            logger.info("🟢 开始调用存储过程..."+ LocalDateTime.now());
            resultRepository.saveResult();
            logger.info("🟢 开始清空结果表..."+ LocalDateTime.now());
            resultRepository.clearResultTable();
            logger.info("🟢 任务结束...本次处理记录数: {}", dataNode.size());
        } catch (Exception e) {
            e.printStackTrace(); // 实际项目中应使用日志记录
        }
    }

    public void saveResultsInBatch(JsonNode dataNode) {
        List<CalculationResult> calculationResults = new ArrayList<>();

        // 收集数据
        for (JsonNode item : dataNode) {
            CalculationResult result = new CalculationResult();
            result.setJh(item.get("JH").asText());
            result.setGkzd(item.get("GTZD").asText());
            result.setDym(item.get("DYM").asText());
            result.setCylGtmj(item.get("CL").asText());
            result.setId(item.has("ID") ? item.get("ID").asText() : null);
            result.setStroke(item.has("STROKE") ? item.get("STROKE").asDouble() : null);
            result.setFrequency(item.has("FREQUENCY") ? item.get("FREQUENCY").asDouble() : null);
            result.setSuspMaxLoad(item.has("SUSP_MAX_LOAD") ? item.get("SUSP_MAX_LOAD").asDouble() : null);
            result.setSuspMinLoad(item.has("SUSP_MIN_LOAD") ? item.get("SUSP_MIN_LOAD").asDouble() : null);
            result.setUpgoingMaxCurrent(item.has("UPGOING_MAX_CURRENT") ? item.get("UPGOING_MAX_CURRENT").asDouble() : null);
            result.setDowngoingMaxCurrent(item.has("DOWNGOING_MAX_CURRENT") ? item.get("DOWNGOING_MAX_CURRENT").asDouble() : null);

            result.setDisplacenent(item.has("DISPLACEMENT") ? item.get("DISPLACEMENT").asText() : null);
            result.setDispLoad(item.has("DISP_LOAD") ? item.get("DISP_LOAD").asText() : null);
            result.setDispCurrent(item.has("DISP_CURRENT") ? item.get("DISP_CURRENT").asText() : null);
            result.setActivePower(item.has("ACTIVE_POWER") ? item.get("ACTIVE_POWER").asText() : null);

            result.setGggf(item.has("GGGF") ? item.get("GGGF").asDouble() : null);
            result.setGgcd(item.has("GGCD") ? item.get("GGCD").asDouble() : null);
            result.setCyggf1(item.has("CYGGF1") ? item.get("CYGGF1").asDouble() : null);
            result.setCygcd1(item.has("CYGCD1") ? item.get("CYGCD1").asDouble() : null);
            result.setCyggf2(item.has("CYGGF2") ? item.get("CYGGF2").asDouble() : null);
            result.setCygcd2(item.has("CYGCD2") ? item.get("CYGCD2").asDouble() : null);
            result.setYy(item.has("YY") ? item.get("YY").asDouble() : null);
            result.setTy(item.has("TY") ? item.get("TY").asDouble() : null);
            result.setHs(item.has("HS") ? item.get("HS").asDouble() : null);
            result.setBj(item.has("BJ") ? item.get("BJ").asDouble() : null);
            result.setBs(item.has("BS") ? item.get("BS").asDouble() : null);
            result.setDynaCreateTime(item.has("DYNA_CREATE_TIME") ? item.get("DYNA_CREATE_TIME").asText() : null);
            result.setCheckDate(item.has("CHECK_DATE") ? item.get("CHECK_DATE").asText() : null);

            // 添加到结果列表中
            calculationResults.add(result);
        }

        // 批量插入数据
        resultRepository.saveBatchResults(calculationResults);
    }

}